package com.example.netty_pipline.service;

import com.example.netty_pipline.pipeline.ChannelPipeline;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Pipeline演示服务 - 展示Pipeline的使用
 */
@Service
public class PipelineDemoService {
    
    @Autowired
    private ChannelPipeline messagePipeline;
    
    @PostConstruct
    public void init() {
        System.out.println("=== Pipeline Demo Service Started ===");
        System.out.println("Pipeline name: " + messagePipeline.name());
        System.out.println("=== Starting Demo ===");
        
        // 演示入站事件处理
        demoInboundProcessing();
        
        // 演示出站事件处理
        demoOutboundProcessing();
        
        System.out.println("=== Demo Completed ===");
    }
    
    /**
     * 演示入站事件处理
     */
    private void demoInboundProcessing() {
        System.out.println("\n--- Inbound Processing Demo ---");
        
        // 模拟接收字节数据
        byte[] messageBytes = "Hello, Pipeline!".getBytes();
        
        // 触发入站事件
        messagePipeline.fireChannelActive();
        messagePipeline.fireChannelRead(messageBytes);
        messagePipeline.fireChannelReadComplete();
        messagePipeline.fireUserEventTriggered("Custom Event");
        messagePipeline.fireChannelInactive();
    }
    
    /**
     * 演示出站事件处理
     */
    private void demoOutboundProcessing() {
        System.out.println("\n--- Outbound Processing Demo ---");
        
        // 模拟出站操作
        messagePipeline.bind("localhost:8080");
        messagePipeline.connect("remote-server:9090", "localhost:8080");
        messagePipeline.write("Hello from Pipeline");
        messagePipeline.flush();
        messagePipeline.disconnect();
        messagePipeline.close();
    }
    
    /**
     * 处理消息
     */
    public void processMessage(byte[] message) {
        System.out.println("\n--- Processing New Message ---");
        messagePipeline.fireChannelActive();
        messagePipeline.fireChannelRead(message);
        messagePipeline.fireChannelReadComplete();
        messagePipeline.fireChannelInactive();
    }
}